package com.learn.demo.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BIODemoServer {
    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("BIO服务器启动，监听端口: + " + serverSocket.getLocalPort() + "当前线程ID:" + Thread.currentThread().getId() + "线程名NAME：" + Thread.currentThread().getName());
        while (true) {
            Socket accept = serverSocket.accept();
            executorService.execute(() -> {
                handlerMsg(accept);
            });
        }
    }

    public static void handlerMsg(Socket socket) {
        byte[] bytes = new byte[1024];
        InputStream inputStream = null;
        try {
            while (true) {
                inputStream = socket.getInputStream();
                int read = inputStream.read(bytes);
                if (read != -1) {
                    String readLine = new String(bytes, 0, read, "GBK");
                    if (readLine.equalsIgnoreCase("quit")) {
                        break;
                    }
                    System.out.println("收到消息......" + "当前线程ID:" + Thread.currentThread().getId() + "线程名NAME：" + Thread.currentThread().getName());
                    System.out.println(readLine);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
                socket.close();
                System.out.println("接收消息结束。" + "当前线程ID:" + Thread.currentThread().getId() + "线程名NAME：" + Thread.currentThread().getName());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
